package com.im.socket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.im.pojo.ImMq;
import com.im.pojo.ImSend;
import com.im.pojoClass.ImSendList;
import com.im.pojoClass.Result;
import com.im.pojoClass.ResultCode;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Configuration;

import javax.websocket.Session;
import java.io.IOException;

@Configuration
public class RabbitmqReceive {

    @RabbitListener(queues = "im_service")
    public void receive(String msg, Message message, Channel channel) {
        try {
            ImMq imMq = JSON.parseObject(msg, ImMq.class);
//            System.out.println(imMq);

            String data = imMq.getData().toString();
            String id = "";
            ResultCode RESULT_CODE = null;
            switch (imMq.getCode()) {
                case "201":
                    ImSend imSend = JSON.parseObject(data, ImSend.class);
                    id = imSend.getReceive_id();
                    RESULT_CODE = ResultCode.RECEIVE_FRIENDS;
                    break;
                case "202":
                    ImSendList imSendList = JSON.parseObject(data, ImSendList.class);
                    id = imSendList.getImSend().getReceive_id();
                    RESULT_CODE = ResultCode.RECEIVE_MESSAGE;
                    break;
                case "203":
                    ImSend imSend1 = JSON.parseObject(data, ImSend.class);
                    id = imSend1.getSend_id();
                    RESULT_CODE = ResultCode.AGREE_FRIENDS;
                    break;
                case "204":
                    RESULT_CODE = ResultCode.VIDEO;
                    break;
                default:
                    break;
            }

            Session session = IndexWebSocket.user_hash.get(id);
            if (session != null) {
//                System.out.println("session存在");
                try {
                    Result result = new Result(RESULT_CODE, data);
                    String s = JSONObject.toJSONString(result);
                    session.getBasicRemote().sendText(s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}